#!/bin/bash

# Manga Colorizer Installation Script
# This script sets up the entire manga colorizer system

set -e

echo "🎨 Manga Colorizer Installation Script"
echo "======================================"

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# Create necessary directories
echo "📁 Creating directories..."
mkdir -p server/models
mkdir -p server/uploads
mkdir -p deployments/nginx/ssl

# Create .env file if it doesn't exist
if [ ! -f server/.env ]; then
    echo "📝 Creating .env file..."
    cp server/.env.example server/.env
    echo "⚠️  Please edit server/.env with your configuration"
fi

# Create nginx configuration
echo "🔧 Creating nginx configuration..."
cat > deployments/nginx/nginx.conf << EOF
events {
    worker_connections 1024;
}

http {
    upstream api {
        server api:8000;
    }

    server {
        listen 80;
        server_name localhost;

        location / {
            proxy_pass http://api;
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
        }

        location /static {
            alias /app/uploads;
            expires 1d;
            add_header Cache-Control "public, immutable";
        }
    }
}
EOF

# Download models (optional - will be downloaded on first run)
echo "📦 Setting up models..."
echo "Models will be downloaded automatically on first run"

# Build and start services
echo "🚀 Building and starting services..."
docker-compose build
docker-compose up -d

# Wait for services to be ready
echo "⏳ Waiting for services to be ready..."
sleep 30

# Check if services are running
echo "🔍 Checking service health..."
if curl -f http://localhost:8000/api/v1/health > /dev/null 2>&1; then
    echo "✅ API service is running"
else
    echo "❌ API service is not responding"
    echo "Check logs with: docker-compose logs api"
fi

echo ""
echo "🎉 Installation complete!"
echo ""
echo "Services are running at:"
echo "  - API: http://localhost:8000"
echo "  - API Docs: http://localhost:8000/docs"
echo "  - MinIO Console: http://localhost:9001"
echo ""
echo "To stop services: docker-compose down"
echo "To view logs: docker-compose logs -f"
echo "To restart: docker-compose restart"
